<?php defined('SYSPATH') or die('No direct access allowed.');
 
class Controller_Category extends Controller_Site {
    public function action_index(){
        $category_list = ORM::factory('category');
        $category_list=$category_list->order_by('name')->find_all();
        $this->content->set('category_list', $category_list);        
    }
    
    public function action_new(){
        $form = View::factory('category/form')->set('action', URL::site('category/new'));
        $category = ORM::factory('category');
        $form->set('category', $category);
        
        if($this->request->method() == 'POST') {
            try {
                $category = ORM::factory('category');
                $form->set('category', $category);
                $this->processForm($category);
                $this->setFlash('notice', 'Sikeresen felvetted az új kategóriát!');
                $this->request->redirect('category');
            }
            catch (ORM_Validation_Exception $e) {
                $form->set('errors', $e->errors('models'));
            }
        }
        $this->content->set('form', $form);
    }    
    
    public function action_delete(){
        $param=$this->request->param('id');
        $category = ORM::factory('category', $param);
        $category->delete();
        $this->setFlash('notice', 'Sikeresen törölted a kategóriát!');
        $this->request->redirect('category');
    }
    
    public function action_edit(){        
        $param=$this->request->param('id');
        $category = ORM::factory('category', $param);
        $form = View::factory('category/form')->set('action', URL::site('category/edit/'.$param));
        $form->set('category', $category);
        if($this->request->method() == 'POST') {
            try {
                $this->processForm($category);
                $this->setFlash('notice', 'Sikeresen módosítottad a kategóriát!');
                $this->request->redirect('category');
            }
            catch (ORM_Validation_Exception $e) {
                $form->set('errors', $e->errors('models'));
            }
        }
        $this->content->set('form', $form);
    }
    
    protected function processForm($category){
        $category->name = $this->request->post('name');
        $category->description = $this->request->post('description');
        $category->save();
    }
}